<template>
  <div>
    <!-- 表单 -->
    <Form :model="monthForm" style="display: block;">
      <Row gutter="40">
        <i-col span="6">
          <FormItem>
            <Cascader change-on-select :data="organizationList" v-model="monthForm.organization" @on-change="organizationChange" placeholder="所属机构" clearable></Cascader>
          </FormItem>
        </i-col>
        <i-col span="6">
          <FormItem>
            <Select v-model="monthForm.empolyee" placeholder="员工" :clearable="isClearable">
              <Option
                v-for="item in empolyeeList"
                :key="item.key"
                :value="item.key"
              >{{item.value}}-{{item.key}}</Option>
            </Select>
          </FormItem>
        </i-col>
        <i-col span="6">
          <FormItem>
            <Select v-model="monthForm.attendMonth" placeholder="考勤月份" clearable>
              <Option v-for="item in attendMonthList" :key="item" :value="item">{{item}}</Option>
            </Select>
          </FormItem>
        </i-col>
        <i-col span="6">
          <FormItem>
            <Select v-model="monthForm.role" placeholder="所属角色" :clearable="isClearable">
              <Option v-for="item in roleList" :key="item.key" :value="item.key">{{item.value}}</Option>
            </Select>
          </FormItem>
        </i-col>
      </Row>
      <Row>
        <FormItem>
          <Button type="primary" style="margin-right:20px" @click="handleSubmit()">查询</Button>
          <Button @click="handleReset()" :disabled="resetButtonDisabled">重置</Button>
        </FormItem>
      </Row>
    </Form>

    <!-- 查询数据 -->
    <Table :columns="monthColumns" :data="monthData">
      <template slot-scope="{row}" slot="record">
        <a @click="buttonClick(row)">查看</a>
      </template>
    </Table>

    <!-- 分页 -->
    <Page
      :total="total"
      show-sizer
      show-total
      style="text-align:right;margin-top:20px;margin-bottom:30px;"
      @on-change="pageChange"
      @on-page-size-change="pageSizeChange"
      :page-size-opts="pageSizeOptions"
      :current="pageIndex"
      :page-size="pageSize"
      transfer
    ></Page>
  </div>
</template>

<script>
import {exportFile} from "../../../util/util"
import util from "../../../util/util"
export default {
  name:'monthCal',
  props: {
    monthPass: {
      type: String
    }
  },
  data() {
    return {
      monthForm: {
        organization: "",
        empolyee: "",
        attendMonth: "",
        role: ""
      },
      organizationList: [],
      empolyeeList: [],
      attendMonthList: [],
      roleList: [],
      monthColumns: [
        {
          title: "月度",
          key: "monthly",
          fixed: "left",
          width: "150"
        },
        {
          title: "姓名",
          key: "name",
          fixed: "left",
          width: "150"
        },
        {
          title: "工号",
          key: "no",
          align: "center",
          width: "150"
        },
        {
          title: "所属机构",
          key: "organizations",
          width: "260"
        },
        {
          title: "角色",
          key: "role",
          width: "120"
        },
        {
          title: "外出天数",
          key: "count",
          align: "center",
          width: ""
        },
        {
          title: "个人月度外出打卡记录",
          key: "",
          align: "center",
          width: "",
          slot: "record"
        }
      ],
      monthData: [],
      currentRow: "",
      total: 0,
      pageIndex: 1,
      pageSize: 10,
      pageSizeOptions: [5, 10, 15, 20],
      isClearable: true,
      resetButtonDisabled: false,
      pageObj: ""
    };
  },
  
  methods: {
    // 重置
    handleReset() {
      this.monthForm = {
        organization: "",
        empolyee: "",
        attendMonth: "",
        role: ""
      };
      this.monthData=[]
    },

    // 提交
    handleSubmit() {
      // this.pageIndex = 1;
      this.pageSize = 10;
      if (
        !this.monthForm.organization &&
        !this.monthForm.empolyee &&
        !this.monthForm.attendMonth &&
        !this.monthForm.role
      ) {
        this.$Message.error("请至少选择一个条件");
        return;
      }
      let obj = {
        organizationNo: this.monthForm.organization[this.monthForm.organization.length-1],
        no: this.monthForm.empolyee,
        monthly: this.monthForm.attendMonth,
        roleNo: this.monthForm.role,
        index: this.pageIndex,
        pageSize: this.pageSize
      };
      this.pageObj = obj;
      console.log(this.pageObj,"pageObjpageObjpageObjpageObjpageObjpageObjpageObj");
      this.$router.push({
        path: this.$router.path,
        query: this.pageObj
      })
      this.api.outsideByMonth(obj).then(res => {
        this.$emit("modifyMonthFlag", false);
        if (res.code == 200 && res.data != null) {
          this.total = res.data.total;
          this.monthData = res.data.records;
          this.monthData.forEach(element => {
            if (element.monthly) {
              element.monthly =
                element.monthly.substr(0, 4) +
                "年" +
                element.monthly.substr(5, 2) +
                "月";
            }
            if (element.organizationNo && element.organization) {
              element.organizations =
                element.organizationNo + "-" + element.organization;
            }
          });
          this.$Message.info(res.msg);
        } else {
          this.$emit("modifyMonthFlag", true);
          this.monthData = [];
          this.total = 0;
          this.$Message.info(res.msg);
        }
      });
    },

    // 页面提交
    pageSubmit() {
      this.pageObj.index = this.pageIndex;
      this.pageObj.pageSize = this.pageSize;
      this.api.outsideByMonth(this.pageObj).then(res => {
        if (res.code == 200 && res.data != null) {
          this.total = res.data.total;
          this.monthData = res.data.records;
          this.monthData.forEach(element => {
            if (element.monthly) {
              element.monthly =
                element.monthly.substr(0, 4) +
                "年" +
                element.monthly.substr(5, 2) +
                "月";
            }
            if (element.organizationNo && element.organization) {
              element.organizations =
                element.organizationNo + "-" + element.organization;
            }
          });
        } else {
          this.monthData = [];
          this.total = 0;
          this.$Message.info(res.msg);
        }
      });
    },

    // 分页设置
    pageChange(pageIndex) {
      this.pageIndex = pageIndex;
      this.pageSubmit();
    },
    pageSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.pageSubmit();
    },

    //个人月度外出打卡记录
    buttonClick(row) {
      // this.$emit("tabsType", "month");
      sessionStorage.setItem("tabsType" ,"month")
      console.log("跳转");
      // return
      this.$router.push({
        // name: "attendRecordDetails",
        path: "attendRecordDetails",
        query: {
          row: row
        }
      });
    },

    exportExcel() {
      if (
        !this.monthForm.organization &&
        !this.monthForm.empolyee &&
        !this.monthForm.attendMonth &&
        !this.monthForm.role
      ) {
        this.$Message.error("请至少选择一个条件");
        return;
      }
      let obj = {
        organizationNo: this.monthForm.organization[this.monthForm.organization.length-1],
        no: this.monthForm.empolyee,
        monthly: this.monthForm.attendMonth,
        roleNo: this.monthForm.role,
        loginNo: sessionStorage.getItem("useragentcode")
      };
      exportFile("scrm-gateway/scrm-uer/api/export/uerOutsideMmExport",obj)
      // let url = "../rest/export/uerOutsideMmExport";
      // window.open(
      //   url +
      //     "?organizationNo=" +
      //     obj.organizationNo +
      //     "&no=" +
      //     obj.no +
      //     "&monthly=" +
      //     obj.monthly +
      //     "&roleNo=" +
      //     obj.roleNo +
      //     "&loginNo=" +
      //     obj.loginNo
      // );
    },

    // 获取当前机构及以下
    getOrganizationList() {
      this.api.remanagecomList().then(res => {
        if (res.code == 200 && res.data != null) {
          let arr = []
          arr.push(res.data)
          arr.forEach(one=>{
            one.value = one.comcode
            one.label = one.comcode + '-' + one.name
            one.children = one.chilDren || []
            if (one.children) {
              one.chilDren.forEach(two=>{
                two.value = two.comcode
                two.label = two.comcode + '-' + two.name
                two.children = two.chilDren || []
                if (two.children) {
                  two.children.forEach(three=>{
                    three.value = three.comcode
                    three.label = three.comcode + '-' + three.name
                    three.children = three.chilDren || []
                    if (three.children) {
                      three.children.forEach(four=>{
                        four.value = four.comcode
                        four.label = four.comcode + '-' + four.name
                        four.children = four.chilDren || []
                      })
                    }
                  })
                }
              })
            }
          })
          console.log(arr);
          this.organizationList = arr
          // this.Echo()
        } else {
          this.organizationList = [];
        }
      });
      this.api.organizationDict().then(res => {
        if (res.code == 200) {
          if (res.data.length > 0) {
            let a = JSON.stringify(res.data[0].map);
            if (a !== "{}") {
              let b = a.substr(1, a.length - 2);
              let c = b.split(",");
              c.forEach(element => {
                let d = element.split(":");
                this.roleList.push({
                  key: d[0].replace(/\"/g, ""),
                  value: d[1].replace(/\"/g, "")
                });
              });
            }
            // if (res.data[0].listKeyValueVOS.length > 0) {
            //   this.organizationList = res.data[0].listKeyValueVOS;
            // }
            // 角色是外勤的处理
            if (this.roleList.length == 1 && this.roleList[0].key == 1) {
              this.isClearable = false;
              this.resetButtonDisabled = true;
              this.monthForm.organization = this.organizationList[0].value;
              this.organizationChange([this.monthForm.organization]);
              this.monthForm.role = this.roleList[0].key;
            }
          }
        } else {
          this.$Message.error(res.msg);
        }
      });
      this.api.getAkkMonthly().then(res => {
        if (res.code == 200) {
          this.attendMonthList = res.data;
        }
      });
    },

    // 机构改变，查询员工
    organizationChange(value) {
      if (value) {
        this.monthForm.empolyee = "";
        if (value) {
          let obj = {
            managecom: value
          };
          $.ajax("scrm-gateway/scrm-uer/api/uerList/selectuser/" + value[value.length-1], {
            method: "get",
            contentType: "application/json;charset=utf-8",
            beforeSend: function(xhr) {
              xhr.setRequestHeader(
                "Authorization",
                sessionStorage.getItem("credentials")
              );
            },
            success: res => {
              if (res.data.length > 0) {
                this.empolyeeList = res.data;
                // 外勤时固定人员
                if (this.roleList.length == 1 && this.roleList[0].key == 1) {
                  this.monthForm.empolyee = this.empolyeeList[0].key;
                }
              } else {
                this.empolyeeList = [];
              }
            },
            error: res => {
              this.$Message.error(res.msg);
            }
          });
        }
      } else {
        this.empolyeeList = [];
        this.monthForm.empolyee = "";
      }
    },
      Echo(){
      this.jsonData = util.GetRequest(decodeURI(location.hash)) || {}
      console.log(this.jsonData,"406")
      if(this.jsonData.organizationNo || this.jsonData.no || this.jsonData.monthly || this.jsonData.roleNo || (this.jsonData.index || this.pageIndex != "1")){
        let arr = []
        this.organizationList.forEach(one =>{
          if(one.value == this.jsonData.organizationNo){
            arr.push(one.value)
          }else if(one.children){
            one.children.forEach(tow =>{
              if(tow.value == this.jsonData.organizationNo){
                arr.push(one.value,tow.value)
              }else if(tow.children){
                tow.children.forEach(three =>{
                  if(three.value == this.jsonData.organizationNo){
                    arr.push(one.value,tow.value,three.value)
                  }else if(three.children){
                    three.children.forEach(four =>{
                      if(three.value == this.jsonData.organizationNo){
                        arr.push(one.value,tow.value,three.value,four.value)
                      }
                    })
                  }
                })
              }
            })
          }
        })
        this.monthForm.organization = arr
        // this.pageIndex = parseInt(this.jsonData.index)
        this.organizationChange(this.monthForm.organization)
        this.monthForm.empolyee = this.jsonData.no
        this.monthForm.attendMonth = this.jsonData.monthly
        this.monthForm.role = this.jsonData.roleNo
        this.handleSubmit()
      }else{
        // this.handleSubmit()
      }
    },
  },
  watch: {
    monthPass: function(val, oldval) {
      this.exportExcel();
    }
  },
  mounted() {
    // 获取当前机构及以下
    this.getOrganizationList();
  },
  beforeDestroy() {
    this.monthForm = null;
    this.organizationList = null;
    this.empolyeeList = null;
    this.attendMonthList = null;
    this.roleList = null;
    this.monthColumns = null;
    this.monthData = null;
    this.currentRow = null;
    this.total = null;
    this.pageIndex = null;
    this.pageSize = null;
    this.pageSizeOptions = null;
    this.isClearable = null;
    this.resetButtonDisabled = null;
    this.pageObj = null;
  }
};
</script>

<style lang="less" scoped>
@import "./dayCount.less";
</style>

<style>
</style>